package com.example.musicplayer.fragment.musicmenu;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.musicplayer.R;
import com.example.musicplayer.activity.BaseActivity;
import com.example.musicplayer.activity.MusicMenuActivity;
import com.example.musicplayer.activity.MusicMenuDisplayActivity;
import com.example.musicplayer.activity.MusicMenuManageActivity;
import com.example.musicplayer.commonUtils.ToastUtil;
import com.example.musicplayer.dialogTools.CreateMusicMenuDialog;
import com.example.musicplayer.fragment.BaseFragment;
import com.example.musicplayer.musicClass.MusicInfo;
import com.example.musicplayer.musicClass.MusicMenu;
import com.example.musicplayer.settings.MusicPlayerSettings;
import com.example.musicplayer.view.MusicMenuSimpleDisplay;
import com.example.musicplayer.view.SimpleDisplayView;

import java.util.ArrayList;
import java.util.List;

public class MyMusicMenuFragment extends BaseFragment implements MusicMenuSimpleDisplay.CallBack {
    private static final int RE_UPDATE_TIME_DELAY = 100;
    private LinearLayout mMusicMenuContainer;
    private TextView mTextViewInfo;
    private ImageView mImageViewAdd;
    private ImageView mImageViewManage;
    private List<MusicMenu> mMusicMenus = new ArrayList<MusicMenu>();
    private final List<MusicMenuSimpleDisplay> mDisplay = new ArrayList<MusicMenuSimpleDisplay>();
    private boolean mNeedUpdateView = true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_my_music_menu, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        addListener();
        updateTextViewInfo();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //初始化歌单项视图并添加
        for (int i = mMusicMenus.size() - 1; i >= 0; i--)
            addNewMusicMenuView(false);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mNeedUpdateView) {
            bindMusicMenuView(0);
            mNeedUpdateView = false;
        }
    }

    private void initView() {
        if (getView() != null) {
            mMusicMenuContainer = getView().findViewById(R.id.linear_layout_music_menu_container);
            mTextViewInfo = getView().findViewById(R.id.textview_music_menu_list_head);
            mImageViewAdd = getView().findViewById(R.id.imageview_music_menu_list_head_add);
            mImageViewManage = getView().findViewById(R.id.imageview_music_menu_list_head_manage);
        }
        mMusicMenus = MusicInfo.getMusicMenus();
    }

    private void addListener() {
        mImageViewAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickAdd();
            }
        });
        mImageViewManage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickManage(-1);
            }
        });
    }

    //歌单项添加点击事件
    private void addListener(final MusicMenuSimpleDisplay display) {
        display.getView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (display.getMusicMenu() != null) {
                    jumpToMusicMenuDisplayActivity(display.getMusicMenu().getName());
                }
            }
        });
        display.getView().setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                clickManage(display.getMusicMenu().getOrder());
                return true;
            }
        });
        display.getImageViewBitmap().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (display.getMusicMenu() != null) {
                    jumpToMusicMenuDisplayActivity(display.getMusicMenu().getName());
                }
            }
        });
        display.getImageViewBitmap().setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                clickManage(display.getMusicMenu().getOrder());
                return true;
            }
        });
        display.setCallBack(this);
    }

    //更新歌单数量信息
    private void updateTextViewInfo() {
        int num = mMusicMenus.size();
        String text = num + "张歌单";
        mTextViewInfo.setText(text);
    }

    //添加新的歌单列表项
    private void addNewMusicMenu(String musicMenuName) {
        MusicMenu musicMenu = MusicInfo.createMusicMenu(musicMenuName);
        if (musicMenu != null) {
            addNewMusicMenuView(true);
            updateMusicMenuView(0, musicMenu);
            mDisplay.get(0).updateMenuCover();
        }
    }

    //在第一个位置插入歌单项视图
    private void addNewMusicMenuView(boolean atFirst) {
        MusicMenuSimpleDisplay display = new MusicMenuSimpleDisplay(SimpleDisplayView.TYPE_DISPLAY);
        RelativeLayout view = display.getView();
        if (atFirst) {
            mMusicMenuContainer.addView(view, 0);
            mDisplay.add(0, display);
        } else {
            mMusicMenuContainer.addView(view);
            mDisplay.add(display);
        }
        addListener(display);
        updateTextViewInfo();
    }

    //绑定歌单视图
    private void bindMusicMenuView(long delayMill) {
        postDelayed(new Runnable() {
            @Override
            public void run() {
                updateMusicMenuView();
            }
        }, delayMill);
    }

    //更新歌单项展示视图
    private void updateMusicMenuView() {
        for (int i = 0; i < mMusicMenus.size(); i++) {
            MusicMenu musicMenu = mMusicMenus.get(i);
            updateMusicMenuView(musicMenu.getOrder(), musicMenu);
        }
        for (int i = 0; i < MusicPlayerSettings.getThreadLoadMenuCover(); i++) {
            updateMenuCover(i);
        }
    }

    //更新指定索引的视图
    private void updateMusicMenuView(int index, MusicMenu musicMenu) {
        if (index >= 0 && index < mDisplay.size()) {
            mDisplay.get(index).update(musicMenu);
        }
    }

    //添加歌单
    private void clickAdd() {
        final Context context = getContext();
        if (context != null) {
            final CreateMusicMenuDialog dialog = new CreateMusicMenuDialog(context);
            dialog.getConfirm().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String content = dialog.getInput();
                    if ("".equals(content)) {
                        ToastUtil.makeToast(getString(R.string.music_menu_name_empty));
                    } else if (MusicInfo.hasMusicMenu(content)) {
                        ToastUtil.makeToast(getString(R.string.music_menu_name_exist));
                    } else {
                        addNewMusicMenu(content);
                        dialog.dismiss();
                    }
                }
            });
            dialog.show();
        }
    }

    //管理自建歌单
    private void clickManage(int defaultSelected) {
        FragmentActivity activity = getActivity();
        if (mMusicMenus.size() > 0 && activity != null) {
            Intent intent = new Intent(activity, MusicMenuManageActivity.class);
            intent.putExtra(MusicMenuManageActivity.CONFIRM_CODE, MusicMenuActivity.TAG);
            intent.putExtra(MusicMenuManageActivity.DEFAULT_SELECTED, defaultSelected);
            startActivityForResult(intent, 1);
            if (activity instanceof BaseActivity) {
                ((BaseActivity) activity).setPendingTransition(R.anim.music_menu_manage_activity_enter, R.anim.fake_anim);
            }
        }
    }

    //跳转到歌单详情界面
    private void jumpToMusicMenuDisplayActivity(String musicMenuName) {
        Intent intent = new Intent(getContext(), MusicMenuDisplayActivity.class);
        intent.putExtra("musicMenuName", musicMenuName);
        startActivityForResult(intent, 1);
        if (getActivity() instanceof BaseActivity) {
            ((BaseActivity) getActivity()).setPendingTransition(R.anim.normal_activity_enter, R.anim.slow_activity_exit);
        }
    }

    //删除或者调整歌单顺序后更新
    public void updateStateChanged() {
        int num = mDisplay.size() - mMusicMenus.size();
        for (int i = 1; i <= num; i++) {
            mDisplay.remove(mDisplay.size() - 1);
            mMusicMenuContainer.removeViewAt(mMusicMenuContainer.getChildCount() - 1);
        }
        updateTextViewInfo();
        bindMusicMenuView(RE_UPDATE_TIME_DELAY);
    }

    private void updateMenuCover(int position) {
        if (position < mDisplay.size()) {
            mDisplay.get(position).updateMenuCover();
        }
    }

    @Override
    public void updateSuccess(int order) {
        updateMenuCover(order + MusicPlayerSettings.getThreadLoadMenuCover());
    }
}